//
//  DataBaseMovie.m
//  UI豆瓣2
//
//  Created by dllo on 15/11/7.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "DataBaseMovie.h"
#import "FMDatabase.h"
#import "Movie.h"
@interface DataBaseMovie ()

@property (nonatomic, retain)FMDatabase *db;

@end

@implementation DataBaseMovie

+ (instancetype)shareDataBase{
    static DataBaseMovie *dbMovie = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dbMovie = [[DataBaseMovie alloc] init];
    });
    return dbMovie;
}
- (void)openDB{
    if (self.db != nil ) {
        NSLog(@"数据库已经打开");
        return;
    }
    
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *fileName = [doc stringByAppendingPathComponent:@"Movie.sqlite"];
    NSLog(@"fileName = %@", fileName);
    
    self.db = [FMDatabase databaseWithPath:fileName];
    
    if ([self.db open]) {
        NSLog(@"数据库打开成功");
    }else {
        NSLog(@"数据库打开失败");
    }
}

- (void)createTable{
    /*movieId release];
     [_movieName release];
     [_pic_url*/
    BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS movie (id INTEGER PRIMARY KEY AUTOINCREMENT, movieId TEXT, movieName TEXT, pic_url TEXT);"];
    if (result) {
        NSLog(@"创表成功");
    }else{
        NSLog(@"创表失败");
    }

}
- (void)insertMovie:(Movie *)movie{
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO movie(movieId, movieName, pic_url) VALUES('%@', '%@', '%@')", movie.movieId, movie.movieName, movie.pic_url];
    BOOL result = [self.db executeUpdate:sql];
    if (result) {
        NSLog(@"插入成功");
    }else{
        NSLog(@"插入失败");
    }
}

- (void)dropTable{
    NSString *sql = [NSString stringWithFormat:@"DROP TABLE movie"];
    BOOL result = [self.db executeUpdate:sql];
    if (result) {
        NSLog(@"删表成功");
    }else {
        NSLog(@"删表失败");
    }
}
- (NSMutableArray *)selectMovie{
    NSMutableArray *array = [NSMutableArray array];
    FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM movie"];
    while ([resultSet next]) {
        NSString *num = [resultSet objectForColumnName:@"movieId"];
        NSString *nameStr = [resultSet objectForColumnName:@"movieName"];
        NSString *img = [resultSet objectForColumnName:@"pic_url"];
        Movie *movie = [[Movie alloc] init];
        movie.movieId = num;
        movie.movieName = nameStr;
        movie.pic_url = img;
        [array addObject:movie];
    }
    
    return array;
}


@end
